package com.gj.xxl.job.admin.controller;

import com.gj.xxl.job.admin.core.entity.JobRegistry;
import com.gj.xxl.job.admin.dao.XxlJobRegistryDAO;
import com.gj.xxl.job.core.biz.model.RegistryParam;
import com.gj.xxl.job.core.biz.model.ReturnT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class ApiController {

    private static final Logger logger = LoggerFactory.getLogger(ApiController.class);

    @Autowired
    private XxlJobRegistryDAO xxlJobRegistryDAO;

    @PostMapping("/api/registry")
    public ReturnT<String> registry(@RequestBody RegistryParam registryParam) {
        JobRegistry jobRegistry = new JobRegistry();
        BeanUtils.copyProperties(registryParam, jobRegistry);
        jobRegistry.setRegistryGroup("EXECUTOR");
        jobRegistry.setUpdateTime(new Date());
        int insert = 0;
        try {
            insert = xxlJobRegistryDAO.insert(jobRegistry);
        } catch (DuplicateKeyException e) {
            logger.info(">>>>>>>>>>>>>> 执行器不是第一注册了, appname = " + registryParam.getRegistryKey());
            //不是第一次注册了，相当于心跳检测，续期一下就行了
            xxlJobRegistryDAO.renewUpdateTime(jobRegistry);
        }

        return ReturnT.SUCCESS;
    }
}
